//初始化所有下拉框
function initSelect(divId){
	
	$("#"+divId+" select").each(function(){
		
		var paraCode=this.id;
		if(paraCode=="floatType"){
			var dataList= getParameterService03("floatingWay","GP");
			formatterSelectControl(dataList,"#"+paraCode);
		}else if(paraCode=="baseAssetType"){
			var dataList= getParameterService03("baseAssetType","LD");
			formatterSelectControl(dataList,"#"+paraCode);
		}else{
			var dataList=getParameterService03(paraCode,"GP");
			if(!!dataList&&dataList.length>0){
				formatterSelectControl(dataList,"#"+paraCode);
			}
		}
	});
	
}

//初始化数据
function initData(divId,jsonData){
	var isUpload="0";
	//设置数据
	setFormData(divId,jsonData);
	//是否已上传附件
	if(!!jsonData.attachList&&jsonData.attachList.length>0){
		isUpload="1";
	}
	var statusVal=formatterParamList(jsonData.status, null, witnessStatusParamList);
	$("#status").html(statusVal);
	
	$('#uploadattachFlg').val(isUpload);
	
	var floating = $("#interestRateMode").val();
	if(floating=='2'){
		//利率模式为浮动时，才显示浮动方式和浮动比例
		$("#floating").show();
	}else{
		$("#floating").hide();
	}
}

function setFormData(divId, jsonData) {
		var divObj = $("#" + divId);	
		divObj.find("input,select,textarea").each(function(){
			if($(this).is('input')){
				if(this.type=='text'){
					var value = jsonData[this.name];
					//对日期处理
					if(this.name.substr(this.name.length-2,2)=='Dt'){
						if(value!=null && value!='' && value.length>10){
							$(this).val(value.substr(0,10));
						}else{
							$(this).val(value);
						}
					}else if($(this).hasClass("numberFormated")){//如果是金额，需要转换成金额显示方式才行
						if (!isNaN(value)) {
							if($(this).hasClass("amtSwitchMillion"))//金额转万元
							{
								 value = parseFloat(value/10000);
							}else{
								value = parseFloat(value);
							}
	                        $(this).val(value);
	                        formatAmountOnBlurByPattern(this,10000);
					  	}
					}else{
						$(this).val(value);
					}
				}else if(this.type=='radio'){
					if(this.value == jsonData[this.name]){
						this.checked = true;
					}
				}else{
					$(this).val(jsonData[this.name]);
				}
			}else if($(this).is('select')){
				$(this).val(jsonData[this.name]);
			}else if($(this).is('textarea')){//火狐换行问题
				$(this).text($(this).val(jsonData[this.name]));
			}
	});
	//显示已经绑定的EOA审批链信息
	//getEoaInfoByLpId(jsonData['eoaApproveId']);
}

//附件上传
var fileIndex=1;
var AttachUpload = function() {
	var oFile = new Object();
	//初始化fileinput控件（第一次初始化）
	oFile.Init = function(divId,ctrlName, uploadUrl) {
		var control = $("#"+divId).find("#"+ctrlName);
		//初始化上传控件的样式
		control.fileinput({
			language : 'zh', //设置语言
			uploadUrl : uploadUrl, //上传的地址
			showRemove : false,
			showUpload : false, //是否显示上传按钮
			showCancel : false, //是否显示取消按钮
			showPreview : false, //是否小窗口预览
			browseClass : "btn btn-default", //按钮样式
			dropZoneEnabled : false,//是否显示拖拽区域
			overwriteInitial : false,
			uploadExtraData:{'handlerName':'uploadAttach'},
			maxFileCount : 1, //表示允许同时上传的最大文件个数
			allowedFileExtensions : [ 'doc','docx','xls','mht','xlsx','ppt','htm','html','txt','zip','rar','gz','bz2','jpg','png','bmp','jpeg','gif','pdf' ],//接收的文件后缀
			msgValidationError: '文件超过10M！',
			enctype : 'multipart/form-data',
			validateInitialCount : false 
		}).on("filebatchselected", function(event, files) {
			if(files.length>0){
				if(files[0].size > 10240000){
					QEX.alert({
						message : "对不起，您上传的文件" + files[0].name + "超过10M，请重新上传。"
					});
					$(this).fileinput('clear'); //清空文件框
					$(this).fileinput('enable'); //清空文件框
					return;
				}
				if(files[0].size == 0){
					QEX.alert({
						message : "对不起，您上传的文件" + files[0].name + "大小为0KB，请重新上传。"
					});
					$(this).fileinput('clear'); //清空文件框
					$(this).fileinput('enable'); //清空文件框
					return;
				}
				$(this).fileinput("upload");
			}
		});
		//文件上传完成之后的事件
		$(control).on("fileuploaded", function(event, data, errorMsg, index) {
			var data = data.response;
			if (data.success) {
				data=data.fileList[0];
				var map={};
	 			map.attachName=data.originName;
	 			map.fileId=data.value;
	 			map.userId=$("#userNo").val();
	 			map.userName=$("#userNo").val();
	 			map.attachSource="10";
	 			addNewFile("#attachmentTableUpload",map);
	 			addNewFile("#attachmentTableUpdate",map);
	 			$("#btnSubmit2").removeAttr("disabled");
			} else {
				QEX.alert({
					message : data.message
				});
				$(this).fileinput('clear'); //清空文件框
				$(this).fileinput('enable'); //清空文件框
				//$('#myModal1').css({'overflow-y':'scroll'});
			}
		});

		$(control).on('fileuploaderror', function(event, data, errorMsg, index) {
				QEX.alert({
					message : errorMsg
					
				});
				$(this).fileinput('clear'); //清空文件框
				$(this).fileinput('enable'); //清空文件框
		});
	}
	return oFile;
};

function delAttachMent(fileId,divId){
	$(divId).bootstrapTable("remove",{'field':'fileId',values:[fileId]});
	$("#btnSubmit2").removeAttr("disabled");
}	

function showAttachMent(fileId){
	if(fileId==null || fileId==""){
		QEX.alert({ title:"提示",message: "附件未上传不能进行下载!" });
		$('#myModal1').css({'overflow-y':'scroll'});
		return false;
	} 
	attachmentForm.action = baseUrl +"fileDownload?fileId="+fileId;
	attachmentForm.submit();
}

function initAttachmentTable(divId, tableJson){
	if(!tableJson || tableJson.length <= 0){
		return ;
	}
	fileIndex = 1;	//初始化上传资的序列号
	for(var i=0; i< tableJson.length;i++){
		addNewFile(divId,tableJson[i]);
	}
}

/**
 * 新增附件
 */
function addNewFile(divId,data){
	$(divId).bootstrapTable("append",
	{
		fileIndex : fileIndex,
		fileId : data.fileId,
		fileName : data.attachName.substring(0,data.attachName.lastIndexOf(".")),
		suffix : data.attachName.substr(data.attachName.lastIndexOf(".")+1),
		result : '成功',
		attachName : data.attachName
	});
	fileIndex++;
}

//保存附件数据
function saveAttachList(){
	var data =new Object();
	data.serviceId="remoteService";
	var  wiId = $("#wiId").val();
	data.lpId = wiId ;
	data.attachList = $("#attachmentTableUpload").bootstrapTable("getData");
	
	data.remoteServiceId = "250014";
	data.applyId = $("#wiId").val();
	data.exCode = "75";
	data.attachSource="10";
	var jsonData = JSON.stringify(data);
	$.ajax({
		type : "POST",
		async : false,
		url : baseUrl + "driverAction.do",
		data : jsonData,
		dataType : "json",
		success : function(result) {
			var res = result;
			if(result.success){
				QEX.alert({ title:"提示",message: "附件操作成功！" });
				$('#myModal2').modal('hide');
				//search();//查询按钮
				//只刷新列表
				$('#witnessTb').bootstrapTable('refresh');
			}else{
				QEX.alert({ title:"提示",message: result.msg });
			}
		}
	});
	//清空这些值
	$("#ver").val("");
	$("#btnSubmit").attr("disabled",false);
	$("#btnSave").attr("disabled",false);
}

function uploadFile(id){
	$("#"+id).click();
}

//收集form表单数据
function getJsonData(divId){
	var data=new Object();
	$("#"+divId).find("input,select,textarea").each(function(){
		if($(this).is('input')){
			 if(this.type=="radio"){
				 if(!data[this.name]){
					var value=$("input[name='"+this.name+"']:checked").val();
					if(value!= null || $.trim(value) != '' )
					{
						data[this.name]=$.trim(value);
					}
				 }
			}else if(this.type=="check"){
				if(!data[this.name]){
					var value="";
					var value=$("input[name='"+this.name+"']:checked").each(function(){
						value+=this.value+",";
		            });
					data[this.name]= $.trim(value);
				}
			}else{
				var value=$(this).val();
				if(value!= null || $.trim(value) != '' ){
					if($(this).hasClass("amtSwitchMillion")){//金额万完转换
						value=value.replace(/,/g,"");
						data[this.name]=parseFloat(value*10000);
					}else{
						data[this.name]=$.trim(value);
					}
				}
			}
		}else{
			var value=$(this).val();
			if(value!= null || $.trim(value) != '' ){
				data[this.name]= $.trim(value);
			}
		}
	});
	return data;
}

/**
 * 获得焦点去掉千分位展示
 * @param obj
 */
function formatAmountOnFocus(obj){
	var value = $(obj).val();
	$(obj).val(value.replace(/,/g,""));
}

/**
 * 失去焦点进行千分位展示
 * 
 * @param obj
 */
function formatAmountOnBlur(obj) {
	var value = $(obj).val();
	value=value.replace(/[^\d.]/g,'');
	if (!value) {
		value = 0;
	}
	value = removalComma(value);
	if(value >= Math.pow(10, 13)){
		QEX.alert({ title:"提示",message: "金额数据过大,请小于拾万亿（拾兆）" });
		$('#editWitnessInfo').css({'overflow-y':'scroll'});
		$(obj).val("");
		$(obj).siblings("div[id='"+obj.id+"1']").remove();
		return false;
	}
	$(obj).val(datagridFormatNumber(value));
	var chn = chineseNumber(value);
	if (!isSpace(chn)) {
		$(obj).parent().append('<div class="span_phone_code" id=' + obj.id + 1 + '></div>');
		var $item = $("#" + obj.id + 1);
		$item.text(chn);
		$item.css({
			'width' : chn.length * 12,
			'margin-left' : $(obj).parent().find('.control-label').width() + 5,
			'width' : chn.length * 14 + 20,
			'margin-left' : $(obj).parent().find('.control-label').width() + 5,
			'padding' : '0px 10px',
			'background' : '#fff3eb none no-repeat 10px center',
			'line-height' : '35px',
			'margin-top' : '10px',
			'text-align' : 'center',
			'font-size' : '12px',
			'display' : 'block'
		})
	} else {
		var $item = $("#" + obj.id + 1);
		$item.css({
			'display' : 'none'
		})
	}
}

/**
 * 失去焦点进行千分位展示
 * @param obj
 */
function formatAmountOnBlur2(obj,flag){
	var value = $(obj).val();
	value=value.replace(/[^\d.]/g,'');
	if(!isSpace(value)){
		value = value.replace(/,/g,"");
		if ( !isNaN(value)){
			value=parseFloat(value);
			if(!flag){
				$(obj).val(datagridFormatNumber(value));
			}else{
				$(obj).val(Math.round(value));
			}
			if(obj.name == 'listingPeriod' ){
				if($(obj).val() > 999){
					QEX.alert({ title:"提示",message: "挂牌公告期不能大于999，请重新输入"});
					$('#editWitnessInfo').css({'overflow-y':'scroll'});
					$(obj).val("");
				}
			}else if( obj.name == 'extendDays'){
				if($(obj).val() > 99999){
					QEX.alert({ title:"提示",message: "延长公告期不能大于99999，请重新输入"});
					$('#editWitnessInfo').css({'overflow-y':'scroll'});
					$(obj).val("");
				}
			}else if(obj.name == 'per'){
				if($(obj).val() > 100){
					QEX.alert({ title:"提示",message: "占比不能超过100%，请重新输入"});
					$('#editWitnessInfo').css({'overflow-y':'scroll'});
					$(obj).val("");
				}
			}else if(obj.name == 'listingTerm'){
				if($(obj).val() > 36500){
					QEX.alert({ title:"提示",message: "产品期限(天)不能超过36500，请重新输入"});
					$('#editWitnessInfo').css({'overflow-y':'scroll'});
					$(obj).val("");
				}
			}
		}else{
			QEX.alert({ title:"提示",message: "请输入正确的数据" });
			$('#editWitnessInfo').css({'overflow-y':'scroll'});
			$(obj).val("");
			$(obj).get(0).focus();
		}
	}
}

function formatPerCent(obj){
	if($(obj).val() == null || $(obj).val() == ""){
		$(obj).val("0.00");
	}
}

function removalCommaByPattern(value,pattern) {
	var temp = value;
	if (value) {
		if (value.indexOf(",")) {
			temp = value.replace(/,/g, "");
		}
	}
	return parseFloat(temp).toFixed(pattern == 10000 ? 6:2);
}

function datagridFormatNumberByPattern(num,pattern) {
	num = num + "";
	if (num == null || num == '') {
		return "";
	}
	num = zeroFormat(num+"");// 去掉以0开头非个位数据
	if (isNaN(num) || num > Math.pow(10, 13)) {
		return "金额数据过大,最大限额拾万亿（拾兆）";
	}
	num = num.replace(new RegExp(/(,)/g), '');
	num = toNumber(num, pattern==10000?'#,##0.0000000':'');
	return num;
}

/**
 * 对传入的数字乘以十的指数
 * @param num  被乘的数字
 * @param index 乘以十的倍数
 * @returns {Number} = num*(pow(10,index))
 */
function powTen(num,index){
	if(num == "" || num == null || num == 0){
		return 0.00;
	}
	var arg = num.split(".");   //用小数点切割数字
	var retNum;
	if(arg[1].length > index){
		//当小数位位数小于十的指数index，小数点向右移动index位
		var frontPiont = arg[0] + arg[1].substring(0,index);//整数位
		var backPiont = index == arg[1].length ? null : arg[1].substring(index,arg[1].length);//小数位
		retNum = frontPiont + "." + backPiont;
	}else{
		//当小数位位数大于十的指数index，先去掉小数点，再加上零
		retNum = num.replace(".","");
		var zero = index - arg[1].length;
		for(var i = 0;i < zero;i++){
			retNum += "0";
		}
	}
	
	//去掉数字前面的零
	var removeZeroNum = 0;
	for(var i = 0;i < retNum.length;i++){
		var str = retNum.substring(i,i+1);
		if(str == "0"){
			removeZeroNum += 1;
		}else{
			break;
		}
	}
	if(removeZeroNum > 0){
		return retNum.substring(removeZeroNum,retNum.length);
	}
	return retNum;
	
}
